<template>
	<view class="store-list-container">
		<!-- 头部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="icon">←</text>
			</view>
			<view class="title">门店列表</view>
			<view class="more-btn">
				<text class="icon">⋮</text>
			</view>
		</view>

		<!-- 位置选择和搜索框 -->
		<view class="location-search">
			<view class="search-row">
				<view class="location-picker" @click="showCityPicker">
					<text class="location-icon">📍</text>
					<text class="city-name">{{selectedCity || '苏州市'}}</text>
					<text class="down-arrow">▼</text>
				</view>

				<!-- 使用uView的搜索组件替换原生搜索框 -->
				<view class="search-container">
					<u-search placeholder="请输入门店名称" v-model="searchKeyword" :show-action="false" :clearable="true"
						@search="searchStore" @custom="searchStore" @clear="clearSearch" height="60" margin="0"
						:animation="false" bg-color="#f5f5f5"></u-search>
				</view>
			</view>
		</view>

		<!-- 推荐地址区域 -->
		<view class="address-recommendations">
			<text class="section-title">按地址推荐</text>

			<view class="address-item active">
				<text class="check-icon">✓</text>
				<text class="address-name">北站家庭旅馆附近</text>
				<text class="current-tag">当前位置</text>
				<text class="relocate-btn" @click="relocate">重新定位</text>
			</view>

			<view class="add-address" @click="addAddress">
				<text class="plus-icon">+</text>
				<text class="add-text">新增地址</text>
			</view>
		</view>

		<!-- 推荐门店列表 -->
		<view class="recommended-stores">
			<text class="section-title">推荐门店</text>

			<view v-if="loading" class="loading-state">
				<u-loading-icon text="加载中..." size="18"></u-loading-icon>
			</view>

			<view v-if="!loading && filteredStores.length === 0" class="empty-state">
				<u-empty mode="list" text="附近暂无门店"></u-empty>
			</view>

			<view v-if="!loading && filteredStores.length > 0" class="store-list">
				<view class="store-item" v-for="(store, index) in filteredStores" :key="index"
					@click="selectStore(store)">
					<view class="store-info">
						<text class="store-name">{{ store.name }}</text>
						<text class="store-address">{{ store.distance || '距离未知' }} | {{ store.address }}</text>
					</view>
					<view class="navigate-icon" @click.stop="showStoreMap(store)">
						<text class="navigate-icon">→</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-btn" @click="enterMall">
			进入狗道宠物商城
		</view>
		
		<!-- 省市选择器 -->
		<u-picker :show="showPicker" :columns="cityColumns" @confirm="confirmCityPicker" @cancel="cancelCityPicker" 
			title="选择城市" :loading="cityLoading" @columnChange="columnChange"></u-picker>
	</view>
</template>

<script>
import { getStoreList } from '../../src/api/store'

export default {
	data() {
		return {
			loading: false,
			searchKeyword: '',  // 新增搜索关键词变量
			stores: [],
			selectedCity: '苏州市',
			selectedProvince: '江苏省',
			showPicker: false,
			cityLoading: false,
			cityColumns: [
				// 第一列为省
				[
					{ text: '江苏省', value: '江苏省' },
					{ text: '浙江省', value: '浙江省' },
					{ text: '上海市', value: '上海市' },
					{ text: '北京市', value: '北京市' },
					{ text: '广东省', value: '广东省' }
				],
				// 第二列为市
				[
					{ text: '苏州市', value: '苏州市' },
					{ text: '南京市', value: '南京市' },
					{ text: '无锡市', value: '无锡市' },
					{ text: '常州市', value: '常州市' },
					{ text: '南通市', value: '南通市' }
				]
			],
			// 省市映射关系
			provinceCity: {
				'江苏省': [
					{ text: '苏州市', value: '苏州市' },
					{ text: '南京市', value: '南京市' },
					{ text: '无锡市', value: '无锡市' },
					{ text: '常州市', value: '常州市' },
					{ text: '南通市', value: '南通市' }
				],
				'浙江省': [
					{ text: '杭州市', value: '杭州市' },
					{ text: '宁波市', value: '宁波市' },
					{ text: '温州市', value: '温州市' },
					{ text: '嘉兴市', value: '嘉兴市' },
					{ text: '湖州市', value: '湖州市' }
				],
				'上海市': [
					{ text: '上海市', value: '上海市' }
				],
				'北京市': [
					{ text: '北京市', value: '北京市' }
				],
				'广东省': [
					{ text: '广州市', value: '广州市' },
					{ text: '深圳市', value: '深圳市' },
					{ text: '珠海市', value: '珠海市' },
					{ text: '汕头市', value: '汕头市' },
					{ text: '佛山市', value: '佛山市' }
				]
			}
		}
	},
	computed: {
		// 过滤门店列表
		filteredStores() {
			if (!this.searchKeyword) return this.stores;
			return this.stores.filter(store =>
				store.name.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
				store.address.toLowerCase().includes(this.searchKeyword.toLowerCase())
			);
		}
	},
	onLoad() {
		this.fetchStoreList();
		
		// 初始化省市选择器数据，确保城市列表与当前选择的省份匹配
		const cities = this.provinceCity[this.selectedProvince];
		if (cities) {
			this.cityColumns.splice(1, 1, cities);
		}
	},
	methods: {
		fetchStoreList() {
			this.loading = true;
			getStoreList({
				province: this.selectedProvince,
				city: this.selectedCity
			})
				.then(res => {
					this.stores = res.data || [];
				})
				.catch(err => {
					console.error('获取门店列表失败', err);
					uni.showToast({
						title: '加载门店失败',
						icon: 'none'
					});
				})
				.finally(() => {
					this.loading = false;
				});
		},
		goBack() {
			uni.navigateBack();
		},
		relocate() {
			uni.showToast({
				title: '重新定位中...',
				icon: 'none'
			});
			
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					// 根据经纬度获取城市信息
					this.getCityFromLocation(res.latitude, res.longitude);
				},
				fail: () => {
					uni.showToast({
						title: '定位失败，请检查权限',
						icon: 'none'
					});
				}
			});
		},
		// 根据经纬度获取城市信息
		getCityFromLocation(latitude, longitude) {
			// 这里可以调用地图API获取城市信息，示例中使用模拟数据
			setTimeout(() => {
				this.selectedProvince = '江苏省';
				this.selectedCity = '苏州市';
				// 重新获取门店列表
				this.fetchStoreList();
				
				uni.showToast({
					title: '定位成功：' + this.selectedCity,
					icon: 'success'
				});
			}, 1000);
		},
		addAddress() {
			uni.showToast({
				title: '新增地址功能开发中',
				icon: 'none'
			});
		},
		selectStore(store) {
			// 将选中的门店信息保存到本地
			uni.setStorageSync('selectedStore', store);

			uni.showToast({
				title: '已选择' + store.name,
				icon: 'none',
				duration: 1500,
				success: () => {
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			});
		},
		enterMall() {
			// 返回到商城首页
			uni.switchTab({
				url: '/pages/shop/index'
			});
		},
		showStoreMap(store) {
			// 跳转到地图页面，并传递门店信息
			uni.navigateTo({
				url: `/pages/map-detail/index?id=${store.id}`
			});
		},
		// 新增搜索相关方法
		searchStore() {
			// 搜索处理，使用computed过滤列表
			console.log('搜索关键词:', this.searchKeyword);
		},
		clearSearch() {
			this.searchKeyword = '';
		},
		// 显示城市选择器
		showCityPicker() {
			this.showPicker = true;
		},
		// 确认城市选择
		confirmCityPicker(e) {
			console.log('选择的城市:', e);
			const provinceIndex = e.indexs[0];
			const cityIndex = e.indexs[1];
			
			// 获取选中的省份和城市
			const province = this.cityColumns[0][provinceIndex];
			const city = this.cityColumns[1][cityIndex];
			
			this.selectedProvince = province.value;
			this.selectedCity = city.value;
			
			// 关闭选择器
			this.showPicker = false;
			
			// 重新获取门店列表
			this.fetchStoreList();
		},
		// 取消城市选择
		cancelCityPicker() {
			this.showPicker = false;
		},
		// 监听省份变化，更新城市列表
		columnChange(e) {
			// 如果是第一列（省份）变化
			if (e.columnIndex === 0) {
				const provinceValue = this.cityColumns[0][e.value].value;
				// 更新第二列（城市）数据
				const cities = this.provinceCity[provinceValue];
				// 更新第二列数据
				this.cityColumns.splice(1, 1, cities);
				// 重置第二列选中项为第一项
				return {
					columnIndex: 1,
					value: 0
				};
			}
		}
	}
}
</script>

<style lang="scss">
.store-list-container {
	background-color: #f8f8f8;
	min-height: 100vh;

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 90rpx;
		background-color: #fff;
		padding: 0 30rpx;
		border-bottom: 1rpx solid #eee;

		.back-btn,
		.more-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.icon {
			font-size: 40rpx;
		}

		.title {
			font-size: 34rpx;
			font-weight: 500;
		}
	}

	.location-search {
		padding: 20rpx 30rpx;
		background-color: #fff;

		.search-row {
			display: flex;
			align-items: center;
			width: 100%;

			.location-picker {
				display: flex;
				align-items: center;
				white-space: nowrap;
				padding-right: 20rpx;

				.location-icon {
					font-size: 36rpx;
					margin-right: 10rpx;
				}

				.city-name {
					font-size: 30rpx;
					margin-right: 10rpx;
					max-width: 120rpx;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.down-arrow {
					font-size: 24rpx;
					color: #999;
				}
			}

			.search-container {
				flex: 1;
			}
		}
	}

	.address-recommendations {
		margin-top: 20rpx;
		padding: 0 30rpx;

		.section-title {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 20rpx;
			display: block;
		}

		.address-item {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;

			&.active {
				.address-name {
					color: #f44336;
					font-weight: 500;
				}

				.check-icon {
					color: #f44336;
				}
			}

			.check-icon {
				font-size: 40rpx;
				margin-right: 15rpx;
			}

			.address-name {
				font-size: 30rpx;
				flex: 1;
			}

			.current-tag {
				font-size: 22rpx;
				color: #999;
				background-color: #f5f5f5;
				padding: 4rpx 12rpx;
				border-radius: 4rpx;
				margin-right: 15rpx;
			}

			.relocate-btn {
				font-size: 26rpx;
				color: #f44336;
			}
		}

		.add-address {
			display: flex;
			align-items: center;
			margin-top: 30rpx;

			.plus-icon {
				font-size: 34rpx;
				color: #999;
				margin-right: 15rpx;
			}

			.add-text {
				font-size: 28rpx;
				color: #666;
			}
		}
	}

	.recommended-stores {
		margin-top: 40rpx;
		padding: 0 30rpx;

		.section-title {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 20rpx;
			display: block;
		}

		.store-list {
			.store-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #eee;

				.store-info {
					flex: 1;

					.store-name {
						font-size: 30rpx;
						font-weight: 500;
						margin-bottom: 8rpx;
						display: block;
					}

					.store-address {
						font-size: 24rpx;
						color: #999;
						display: block;
					}
				}

				.navigate-icon {
					font-size: 30rpx;
					color: #ccc;
					margin-left: 15rpx;
				}
			}
		}
	}

	.bottom-btn {
		position: fixed;
		bottom: 40rpx;
		left: 30rpx;
		right: 30rpx;
		height: 90rpx;
		background-color: #fff;
		color: #333;
		font-size: 32rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 45rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		border: 1px solid #ddd;
	}
}
</style>